// 命令行应用程序
#include <QCoreApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QTextStream>
#include <QDateTime>
#include <QHostAddress>
#include <QNetworkInterface>


#include "tcpserver.h"

// 界面应用程序
#include <QApplication>
#include "tcpdialog.h"

// 在main函数中添加获取内网IP的代码
QString getLocalIpAddress() {
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            return ipAddressesList.at(i).toString();
        }
    }
    return "192.168.1.100"; // 默认值
}

// 命令行模式
int CommandLine(const QCoreApplication& app)
{
    QCommandLineParser parser;
    parser.setApplicationDescription("Multi-threaded TCP server using Qt5");
    parser.addHelpOption();
    parser.addVersionOption();

    // 默认监听地址被设置为"0.0.0.0"。这个地址表示监听所有可用的网络接口
//    QCommandLineOption addressOption(QStringList() << "a" << "address",
//                                    "Listen address (default: 0.0.0.0)",
//                                    "address", "0.0.0.0");

    // 然后在创建addressOption时使用这个函数
    QCommandLineOption addressOption(QStringList() << "a" << "address",
                                    "Listen address (default: " + getLocalIpAddress() + ")",
                                    "address", getLocalIpAddress());
    parser.addOption(addressOption);

    QCommandLineOption portOption(QStringList() << "p" << "port",
                                 "Listen port (default: 12345)",
                                 "port", "12345");
    parser.addOption(portOption);

    parser.process(app);

    QString addressStr = parser.value(addressOption);
    quint16 port = parser.value(portOption).toUShort();

    QHostAddress address(addressStr);
    if (address.isNull()) {
        QTextStream(stderr) << "Invalid address: " << addressStr <<"\n";
        return 1;
    }

    // TCP服务器对象
    TcpServer *server = new TcpServer();

    QObject::connect(server, &TcpServer::clientConnected, [&server](qintptr descriptor, const QString &info) {
        QTextStream(stdout) << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                           << " - Client connected: " << descriptor << " - " << info <<"\n";
        //server.broadcastMessage("TcpServer");
        server->sendToClient(descriptor, "Echo: " + QString("我是 TCP服务器对象"));
    });

    QObject::connect(server, &TcpServer::clientDisconnected, [](qintptr descriptor) {
        QTextStream(stdout) << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                           << " - Client disconnected: " << descriptor <<"\n";
    });

    QObject::connect(server, &TcpServer::messageReceived, [&server](qintptr descriptor, const QString &message) {
        QTextStream(stdout) << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                           << " - Message from " << descriptor << ": " << message <<"\n";
        server->sendToClient(descriptor, "Echo: " + message);
    });

    QObject::connect(server, &TcpServer::serverError, [](const QString &error) {
        QTextStream(stdout) << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                           << " - Server error: " << error <<"\n";
    });

    if (!server->startServer(address, port)) {
        return 1;
    }

    QTextStream(stdout) << "Server started on " << address.toString() << ":" << port <<"\n";
    QTextStream(stdout) << "Press Ctrl+C to stop" <<"\n";

    return 0;
}

int main(int argc, char *argv[]) {
    // 命令行-应用程序
//    QCoreApplication app(argc, argv);
//    QCoreApplication::setApplicationName("Qt5 TCP Server");
//    QCoreApplication::setApplicationVersion("1.0");

    // 界面应用程序
    QApplication app(argc, argv);
    QApplication::setApplicationName("Qt5 TCP Server");
    QApplication::setApplicationVersion("1.0");

    TCPDialog tcpServer;
    tcpServer.show();

    return app.exec();
}
